<template>
    <div class="app-container">
        <vxe-grid ref="xGrid" v-bind="gridOptions" @checkbox-change="handleSelectionChange">
            <template #toolbar_buttons>
                <el-row :gutter="10">
                    <el-col :span="1.5">
                        <el-button type="primary" plain icon="Plus" @click="openSelectUser" v-hasPermi="['system:role:add']">添加用户</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="danger" plain icon="CircleClose" :disabled="multiple" @click="cancelAuthUserAll" v-hasPermi="['system:role:remove']">批量取消授权</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="primary" plain icon="Refresh" @click="handleSync" v-hasPermi="['system:role:remove']">同步</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="warning" plain icon="Close" @click="handleClose">关闭</el-button>
                    </el-col>
                    <!-- <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar> -->
                </el-row>
            </template>
            <template #slotStatus="{ row }">
                <dict-tag :options="sys_normal_disable" :value="row.status" />
            </template>
            <template #action="{ row }">
                <el-button link type="primary" icon="CircleClose" @click="cancelAuthUser(row)" v-hasPermi="['system:role:remove']">取消授权</el-button>
            </template>
        </vxe-grid>
        <select-user ref="selectRef" :roleId="queryParams.roleId" @ok="handleQuery" />
    </div>
</template>

<script name="AuthUser" lang="ts">
    import { getCurrentInstance, ref, reactive, defineComponent, unref } from "vue";
    import { useRoute } from "vue-router";
    import selectUser from "./selectUser.vue";
    import XEUtils from "xe-utils";
    import { VxeGridInstance, VxeGridProps, VxeGridListeners } from "../../../../types/index";
    import { allocatedUserList, authUserCancel, authUserCancelAll, syncUser } from "@/api/system/role";
    export default defineComponent({
        components: {
            selectUser,
        },
        setup() {
            const route = useRoute();
            const { proxy } = getCurrentInstance() as any;
            const { sys_normal_disable } = proxy.useDict("sys_normal_disable");
            const xGrid = ref({} as VxeGridInstance);
            const userList = ref([]);
            const loading = ref(true);
            const showSearch = ref(true);
            const multiple = ref(true);
            const total = ref(0);
            const userIds = ref([]);

            const queryParams: any = reactive({
                roleId: route.params.roleId,
            });
            function getTableAction() {
                const tableAction = unref(xGrid);
                if (!tableAction) {
                    throw new Error("tableAction is null");
                }
                return tableAction;
            }
            const gridOptions = reactive<VxeGridProps>({
                border: true,
                resizable: true,
                showHeaderOverflow: true,
                showOverflow: true,
                highlightHoverRow: true,
                keepSource: true,
                id: "4",
                height: "auto",
                rowId: "userId",
                sortConfig: {
                    trigger: "cell",
                    remote: true,
                },
                filterConfig: {
                    remote: true,
                },
                pagerConfig: {
                    pageSize: 10,
                    pageSizes: [5, 10, 15, 20, 50, 100, 200, 500, 1000],
                    perfect: true,
                },
                formConfig: {
                    titleWidth: 100,
                    titleAlign: "right",
                    items: [
                        {
                            field: "userName",
                            title: "用户名称",
                            span: 5,
                            itemRender: { name: "$input", props: { placeholder: "请输入用户名称" } },
                        },
                        {
                            field: "phonenumber",
                            title: "手机号码",
                            span: 5,
                            itemRender: { name: "$input", props: { placeholder: "请输入手机号码" } },
                        },
                        {
                            itemRender: {
                                name: "$buttons",
                                children: [
                                    {
                                        props: {
                                            type: "submit",
                                            content: "查询",
                                            status: "primary",
                                        },
                                    },
                                    {
                                        props: {
                                            type: "reset",
                                            content: "重置",
                                        },
                                    },
                                ],
                            },
                        },
                    ],
                },
                toolbarConfig: {
                    refresh: true,
                    zoom: true,
                    custom: true,
                    slots: {
                        buttons: "toolbar_buttons",
                    },
                },
                proxyConfig: {
                    paramsChangeLoad: false, //额外的请求参数改变时是否重新请求数据
                    seq: true, // 启用动态序号代理，每一页的序号会根据当前页数变化
                    sort: true, // 启用排序代理，当点击排序时会自动触发 query 行为
                    filter: true, // 启用筛选代理，当点击筛选时会自动触发 query 行为
                    form: true, // 启用表单代理，当点击表单提交按钮时会自动触发 reload 行为
                    // 对应响应结果 { result: [], page: { total: 100 } }
                    props: {
                        result: "rows", // 配置响应结果列表字段
                        total: "total", // 配置响应结果总页数字段
                    },
                    ajax: {
                        // 接收 Promise
                        query: ({ page, sorts, filters, form, params }: any) => {
                            const queryParams: any = Object.assign({}, form);
                            // 处理排序条件
                            const orderByColumn = <Array<String>>[];
                            const isAsc = <Array<Boolean>>[];
                            sorts.forEach((m: any) => {
                                orderByColumn.push(m.field);
                                isAsc.push(m.order);
                            });
                            queryParams.orderByColumn = orderByColumn.join(",");
                            queryParams.isAsc = isAsc.join(",");
                            // 处理筛选条件
                            filters.forEach(({ property, values }: any) => {
                                queryParams[property] = values.join(",");
                            });
                            return allocatedUserList({
                                page: {
                                    current: page.currentPage,
                                    size: page.pageSize,
                                },
                                roleId: route.params.roleId,
                                ...queryParams,
                                ...params,
                            }).then((response) => {
                                return response;
                            });
                        },
                    },
                },
                columns: [
                    { type: "checkbox", width: 60 },
                    {
                        field: "userName",
                        title: "用户名称",
                        sortable: true,
                    },
                    {
                        field: "nickName",
                        title: "用户昵称",
                        sortable: true,
                    },
                    {
                        field: "email",
                        title: "邮箱",
                        sortable: true,
                    },
                    {
                        field: "phonenumber",
                        title: "手机",
                        sortable: true,
                    },
                    {
                        field: "status",
                        title: "状态",
                        filters: sys_normal_disable,
                        slots: {
                            default: "slotStatus",
                        },
                    },
                    {
                        field: "createTime",
                        title: "创建时间",
                        visible: false,
                        sortable: true,
                        formatter({ cellValue }: any) {
                            return XEUtils.toDateString(cellValue, "yyyy-MM-dd HH:ss:mm");
                        },
                    },
                    {
                        title: "操作",
                        width: 120,
                        align: "center",
                        fixed: "right",
                        slots: { default: "action" },
                    },
                ],
                checkboxConfig: {
                    labelField: "id",
                    reserve: true,
                    highlight: true,
                    range: true,
                },
            });
            // 返回按钮
            function handleClose() {
                const obj = { path: "/system/role" };
                proxy.$tab.closeOpenPage(obj);
            }
            // /** 搜索按钮操作 */
            function handleQuery() {
                getTableAction().commitProxy("reload");
            }
            // 多选框选中数据
            function handleSelectionChange(selection: any) {
                userIds.value = selection.records.map((item: any) => item.userId);
                multiple.value = !selection.records.length;
            }
            /** 打开授权用户表弹窗 */
            function openSelectUser() {
                proxy.$refs["selectRef"].show();
            }
            /** 取消授权按钮操作 */
            function cancelAuthUser(row: any) {
                proxy.$modal
                    .confirm('确认要取消该用户"' + row.userName + '"角色吗？')
                    .then(function () {
                        return authUserCancel({ userId: row.userId, roleId: queryParams.roleId });
                    })
                    .then(() => {
                        proxy.$modal.msgSuccess("取消授权成功");
                        getTableAction().commitProxy("reload");
                    })
                    .catch(() => {});
            }
            /** 批量取消授权按钮操作 */
            function cancelAuthUserAll(row: any) {
                const roleId = queryParams.roleId;
                const uIds = userIds.value.join(",");
                proxy.$modal
                    .confirm("是否取消选中用户授权数据项?")
                    .then(function () {
                        return authUserCancelAll({ roleId: roleId, userIds: uIds });
                    })
                    .then(() => {
                        proxy.$modal.msgSuccess("取消授权成功");
                        getTableAction().commitProxy("reload");
                        multiple.value = true;
                    })
                    .catch(() => {});
            }
            //从角色表格同步到用户
            function handleSync() {
                const roleId = queryParams.roleId;
                syncUser(roleId).then(() => {
                    proxy.$modal.msgSuccess("操作成功");
                });
            }

            return {
                xGrid,
                queryParams,
                showSearch,
                openSelectUser,
                multiple,
                cancelAuthUserAll,
                handleClose,
                loading,
                userList,
                handleSelectionChange,
                sys_normal_disable,
                cancelAuthUser,
                total,
                gridOptions,
                handleQuery,
                handleSync,
            };
        },
    });
</script>
